﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SQLite;
using System.Diagnostics;

namespace ContactsWeb
{
    public partial class ContactsWeb : Form
    {
        /// <summary>
        /// 导出工作是否进行中
        /// </summary>
        bool ExtractPlaying;

        /// <summary>
        /// 是否在导出时关闭窗口
        /// </summary>
        bool WinFormClose;

        public ContactsWeb()
        {
            InitializeComponent();

            WinFormClose = false;
            ExtractPlaying = false;
            ///暂停键初始不可用
            this.button2.Enabled = false;

            LinkDataBase();
        }

        SQLiteConnection conn;

        private void LinkDataBase()
        {
            //string currentPath = Application.StartupPath;
            //conn = new SQLiteConnection("Data Source='" + currentPath + "\\contacts.db';Pooling=true;FailIfMissing=false");
        }



        HtmlDocument document;

        HtmlElement formElement;
        mshtml.HTMLFormElement form;

        HtmlElement deptElement;
        mshtml.HTMLSelectElement deptSelector;

        HtmlElement personElement;
        mshtml.HTMLSelectElement personSelector;

        HtmlElement btnElement;
        mshtml.HTMLInputElement btn;

        List<string> deptStringList;
        List<string> personStringList;

        private void SelectDept(int index)
        {

        }


        private void button1_Click(object sender, EventArgs e)
        {
            ///导出过程中导出键不可用
            this.button1.Enabled = false;
            ///导出过程中暂停键可用
            this.button2.Enabled = true;
            ///导出过程中统计键不可用
            this.button3.Enabled = false;
            this.button4.Enabled = false;

            ExtractPlaying = true;

            try
            {
                string currentPath = Application.StartupPath;

                string dataFile = "Data Source='" + currentPath + "\\contacts.db'";
                bool isExist = false;
                if (File.Exists(dataFile))
                {
                    isExist = true;
                }

                SQLiteConnection conn = conn = new SQLiteConnection(dataFile + ";Pooling=true;FailIfMissing=false");
                conn.Open();
                SQLiteCommand command = new SQLiteCommand(conn);

                if (!isExist)
                {
                    command.CommandText = @"CREATE TABLE [PERSON] (
    [ID] varchar NOT NULL PRIMARY KEY, 
    [NAME] varchar, 
    [DEPARTMENT] varchar, 
    [MOBILE_PHONE] varchar, 
    [VIRTUAL_PHONE] varchar, 
    [POSITION] varchar, 
    [REGION] varchar, 
    [OFFICE_PHONE] varchar, 
    [INNER_PHONE] varchar, 
    [PY] varchar, 
    [CAR] varchar
)";
                    command.ExecuteNonQuery();
                }

                document = webBrowser1.Document;

                formElement = document.GetElementById("form1");
                form = (mshtml.HTMLFormElement)formElement.DomElement;

                deptElement = document.GetElementById("ddl_depart");
                deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                personElement = document.GetElementById("ddl_person");
                personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                btnElement = document.GetElementById("btn_Query");
                btn = (mshtml.HTMLInputElement)(btnElement.DomElement);


                deptStringList = deptElement.OuterText.Split(new char[] { '—', ' ' })
                        .Where(p => p != string.Empty).Select(p => p.Trim()).ToList();

                List<string> lastPersonStringList = new List<string>();

                int currentDeptIndex = deptSelector.selectedIndex;
                for (int i = (currentDeptIndex == 0 ? currentDeptIndex : currentDeptIndex - 1); i < deptStringList.Count; i++)
                {
                    bool IFailed = true;
                    int IFailedCount = 0;

                    while (IFailed && ExtractPlaying)
                    {
                        try
                        {
                            if (WinFormClose)
                            {
                                break;
                            }

                            bool LoadSuccess = true;

                            deptElement = document.GetElementById("ddl_depart");
                            deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                            formElement = document.GetElementById("form1");
                            form = (mshtml.HTMLFormElement)formElement.DomElement;

                            deptSelector.selectedIndex = i + 1;
                            deptSelector.FireEvent("onchange");
                            form.submit();

                            System.Threading.Thread.Sleep(500);
                            Application.DoEvents();

                            personElement = document.GetElementById("ddl_person");
                            personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                            var tempPersonStringList = personElement.OuterText.Split(new char[] { '—', ' ' })
                                .Where(p => p != string.Empty).Select(p => p.Trim()).ToList();


                            personStringList = new List<string>();
                            //get current dept persons
                            for (int j = 0; j < tempPersonStringList.Count; j++)
                            {
                                if (j % 2 == 1) personStringList.Add(tempPersonStringList[j]);
                            }

                            if (lastPersonStringList.Count == personStringList.Count)
                            {
                                if (lastPersonStringList.Count > 0)
                                {
                                    if (lastPersonStringList[0] == personStringList[0])
                                    {
                                        LoadSuccess = false;
                                    }
                                    else
                                    {

                                        lastPersonStringList.Clear();
                                        foreach (string oneName in personStringList)
                                        {
                                            lastPersonStringList.Add(oneName);
                                        }
                                    }
                                }
                                else
                                {
                                    if (IFailedCount < 5)
                                    {
                                        LoadSuccess = false;
                                    }
                                }
                            }
                            else
                            {

                                lastPersonStringList.Clear();
                                foreach (string oneName in personStringList)
                                {
                                    lastPersonStringList.Add(oneName);
                                }
                            }

                            if (LoadSuccess)
                            {
                                int currentPersonIndex = personSelector.selectedIndex;
                                for (int j = (currentPersonIndex == 0 ? currentPersonIndex : currentPersonIndex - 1); j < personStringList.Count; j++)
                                {
                                    bool JFailed = true;
                                    int JFailedCount = 0;

                                    while (JFailed && ExtractPlaying)
                                    {
                                        try
                                        {
                                            personElement = document.GetElementById("ddl_person");
                                            personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                                            personSelector.selectedIndex = j + 1;
                                            //personSelector.FireEvent("onchange");

                                            //记录下拉框的工号，用于对比判断下面信息是否刷新
                                            string CurrentSelectedID = personSelector.value;

                                            btnElement = document.GetElementById("btn_Query");
                                            btn = (mshtml.HTMLInputElement)(btnElement.DomElement);
                                            btn.click();

                                            System.Threading.Thread.Sleep(200);
                                            Application.DoEvents();

                                            formElement = document.GetElementById("form1");
                                            form = (mshtml.HTMLFormElement)formElement.DomElement;


                                            var tableElement = formElement.GetElementsByTagName("table")[1];
                                            var table = (mshtml.HTMLTable)tableElement.DomElement;

                                            var cells = table.cells.Cast<mshtml.HTMLTableCell>().ToList();

                                            string id = cells[1].innerText.Trim();
                                            if (CurrentSelectedID == id)
                                            {
                                                string name = cells[3].innerText.Trim();
                                                string dept = cells[5].innerText.Trim();
                                                string mobile = cells[7].innerText.Trim();
                                                string virt = cells[9].innerText.Trim();
                                                string position = cells[11].innerText.Trim();
                                                string region = cells[13].innerText.Trim(new char[] { '区', '号', ' ' });
                                                string office = cells[14].innerText.Trim(new char[] { '电', '话', ' ' });
                                                string inner = cells[15].innerText.Trim(new char[] { '分', '机', ' ' });
                                                string car = cells[17].innerText.Trim();

                                                command.CommandText = "select count(*) from [PERSON] where [ID]='" + id + "'";

                                                var result = int.Parse(command.ExecuteScalar().ToString());
                                                if (result == 0)
                                                {
                                                    command.CommandText = string.Format(@"INSERT INTO [PERSON]
        ([ID]
        ,[NAME]
        ,[DEPARTMENT]
        ,[MOBILE_PHONE]
        ,[VIRTUAL_PHONE]
        ,[POSITION]
        ,[REGION]
        ,[OFFICE_PHONE]
        ,[INNER_PHONE]
        ,[PY]
        ,[CAR])
    VALUES
        ('{0}'
        ,'{1}'
        ,'{2}'
        ,'{3}'
        ,'{4}'
        ,'{5}'
        ,'{6}'
        ,'{7}'
        ,'{8}'
        ,'{9}'
        ,'{10}')", id, name, dept, mobile, virt, position, region, office, inner, ConvertHZToPY.ToChineseSpell(name), car);
                                                    command.ExecuteNonQuery();
                                                }
                                                else if (result > 0)
                                                {
                                                    command.CommandText = string.Format(@"UPDATE [PERSON]
    SET [ID] = '{0}'
        ,[NAME] = '{1}'
        ,[DEPARTMENT] ='{2}'
        ,[MOBILE_PHONE] = '{3}'
        ,[VIRTUAL_PHONE] ='{4}'
        ,[POSITION] = '{5}'
        ,[REGION] ='{6}'
        ,[OFFICE_PHONE] ='{7}'
        ,[INNER_PHONE] = '{8}'
        ,[PY]='{9}'
        ,[CAR]='{11}'
    WHERE [ID]='{10}'", id, name, dept, mobile, virt, position, region, office, inner, ConvertHZToPY.ToChineseSpell(name), id, car);
                                                    command.ExecuteNonQuery();
                                                }

                                                JFailed = false;
                                            }
                                            else
                                            {
                                                //如果下拉框和下面信息不一致，本次信息抓取失败，重新抓取
                                                JFailed = true;
                                                JFailedCount++;
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError(ex.Message);

                                            JFailedCount++;

                                            if (JFailedCount > 5)
                                            {
                                                System.Threading.Thread.Sleep(JFailedCount * 200);
                                                Application.DoEvents();
                                            }
                                        }
                                    }

                                }

                                IFailed = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.Message);

                            IFailedCount++;

                            if (IFailedCount > 5)
                            {
                                System.Threading.Thread.Sleep(IFailedCount * 200);
                                Application.DoEvents();
                            }
                        }
                    }
                }
                conn.Close();
            }
            catch
            {
                MessageBox.Show("认证失败，请重新打开本软件");
            }

            ///导出结束后导出键可用
            this.button1.Enabled = true;
            ///导出结束后暂停键不可用
            this.button2.Enabled = false;
            ///导出结束中统计键可用
            this.button3.Enabled = true;
            this.button4.Enabled = true;

            ExtractPlaying = false;

            MessageBox.Show("导出结束！");

            if (WinFormClose)
            {
                this.Close();
            }
        }

        private void ContactsWeb_FormClosed(object sender, FormClosedEventArgs e)
        {
            WinFormClose = true;
            //关闭数据库
            if (conn != null)
            {
                conn.Close();
            }
            //关闭ie独立线程
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ///暂停后暂停键不可用
            this.button2.Enabled = false;
            ///暂停后导出键可用
            this.button1.Enabled = true;
            ///暂停后统计键可用
            this.button3.Enabled = true;
            this.button4.Enabled = true;

            ExtractPlaying = false;
        }

        private void ContactsWeb_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ExtractPlaying)
            {
                if (MessageBox.Show("当前软件仍在导出中，是否中断导出？\n中断导出并退出软件请选“是”，继续导出请选“否”", "是否中断导出",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExtractPlaying = false;

                    e.Cancel = true;

                    WinFormClose = true;
                }
                else
                {
                    e.Cancel = true;
                }

            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            ///统计结束前所有操作键不可用
            this.button3.Enabled = false;
            this.button4.Enabled = false;
            this.button1.Enabled = false;
            this.button2.Enabled = false;

            int TotalClerksCount = 0;
            int TotalDeptCount = 0;

            try
            {
                document = webBrowser1.Document;

                formElement = document.GetElementById("form1");
                form = (mshtml.HTMLFormElement)formElement.DomElement;

                deptElement = document.GetElementById("ddl_depart");
                deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                personElement = document.GetElementById("ddl_person");
                personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                btnElement = document.GetElementById("btn_Query");
                btn = (mshtml.HTMLInputElement)(btnElement.DomElement);


                deptStringList = deptElement.OuterText.Split(new char[] { '—', ' ' })
                        .Where(p => p != string.Empty).Select(p => p.Trim()).ToList();

                TotalDeptCount = deptStringList.Count;
                textBox1.Text = TotalDeptCount.ToString();

                List<string> lastPersonStringList = new List<string>();

                int currentDeptIndex = deptSelector.selectedIndex;
                for (int i = (currentDeptIndex == 0 ? currentDeptIndex : currentDeptIndex - 1); i < deptStringList.Count; i++)
                {
                    bool IFailed = true;
                    int IFailedCount = 0;

                    while (IFailed)
                    {
                        try
                        {
                            if (WinFormClose)
                            {
                                break;
                            }

                            deptElement = document.GetElementById("ddl_depart");
                            deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                            formElement = document.GetElementById("form1");
                            form = (mshtml.HTMLFormElement)formElement.DomElement;

                            deptSelector.selectedIndex = i + 1;
                            deptSelector.FireEvent("onchange");
                            form.submit();

                            System.Threading.Thread.Sleep(300);
                            Application.DoEvents();

                            personElement = document.GetElementById("ddl_person");
                            personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                            var tempPersonStringList = personElement.OuterText.Split(new char[] { '—', ' ' })
                                .Where(p => p != string.Empty).Select(p => p.Trim()).ToList();


                            personStringList = new List<string>();
                            //get current dept persons
                            for (int j = 0; j < tempPersonStringList.Count; j++)
                            {
                                if (j % 2 == 1) personStringList.Add(tempPersonStringList[j]);
                            }

                            if (lastPersonStringList.Count == personStringList.Count)
                            {
                                if (lastPersonStringList.Count > 0)
                                {
                                    if (lastPersonStringList[0] == personStringList[0])
                                    {
                                        IFailed = true;
                                    }
                                    else
                                    {
                                        TotalClerksCount += personStringList.Count;

                                        IFailed = false;

                                        lastPersonStringList.Clear();
                                        foreach (string oneName in personStringList)
                                        {
                                            lastPersonStringList.Add(oneName);
                                        }
                                    }
                                }
                                else if (IFailedCount > 5)
                                {
                                    IFailed = false;
                                }
                            }
                            else
                            {
                                TotalClerksCount += personStringList.Count;
                                textBox2.Text = TotalClerksCount.ToString();

                                IFailed = false;

                                lastPersonStringList.Clear();
                                foreach (string oneName in personStringList)
                                {
                                    lastPersonStringList.Add(oneName);
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.Message);

                            IFailedCount++;

                            if (IFailedCount > 5)
                            {
                                System.Threading.Thread.Sleep(IFailedCount * 200);
                                Application.DoEvents();
                            }
                        }
                    }
                }
            }
            catch { }



            ///统计结束所有操作键可用
            this.button3.Enabled = true;
            this.button4.Enabled = true;
            this.button1.Enabled = true;
            this.button2.Enabled = true;

        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                document = webBrowser1.Document;

                formElement = document.GetElementById("form1");
                form = (mshtml.HTMLFormElement)formElement.DomElement;

                deptElement = document.GetElementById("ddl_depart");
                deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                personElement = document.GetElementById("ddl_person");
                personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                btnElement = document.GetElementById("btn_Query");
                btn = (mshtml.HTMLInputElement)(btnElement.DomElement);

                deptElement = document.GetElementById("ddl_depart");
                deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement);

                formElement = document.GetElementById("form1");
                form = (mshtml.HTMLFormElement)formElement.DomElement;

                deptSelector.selectedIndex = 0;
                deptSelector.FireEvent("onchange");
                form.submit();

                personElement = document.GetElementById("ddl_person");
                personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement);

                personSelector.selectedIndex = 0;

                //Application.DoEvents();

            }
            catch { }
        }
    }

}
